<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="150")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.modal == 'socialSecurityNo'" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) of arrListDown[item.options]"
                  :value="c_item.value"
                  :key="c_index"
                ) {{ c_item.value }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, c_index) in arrListDown[item.options]"
                  :value="c_item.key"
                  :key="c_item.key"
                ) {{ c_item.value }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model1]" :value="datePickerDefault" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model2]" :value="datePickerDefault" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker")
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
              Divider(type="vertical")
              |应付总计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.total}}
              |元
            .pull-right.table-title-btns
              Button.mr-10(v-if="hasImport" type="info" @click="handleShowImportStandingBookModal") 台账导入
              Button.mr-10(v-if="hasExport" type="info" @click="exportSSPayableBillDetail") 导出
              Button.mr-10(v-if="hasExportPayableDetail" type="info" @click="handleShowExportModal") 导出明细
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )
          template(slot-scope="{ row, index }" slot="action")
            Button.mr-10(v-if="hasDelete" type="text" @click="isDeleteModal(row)") 删除
            Button.mr-10(v-if="hasForceDelete" type="text" @click="isForceDeleteModal(row)") 强制删除
            Button.mr-10(v-if="hasExportPayPDF" type="text" @click="getApplyRest(row)") 生成付款单
            Button.mr-10(type="text" @click="gotoDetail(row)") 查看明细
            Button.mr-10(type="text" @click="handleShowLookPayListModal(row)") 查看付款

    //- 台账导入弹窗
    ImportStandingBookModal(ref="ImportStandingBookModal" @uploadSuccess="query")
    //- 付款弹窗
    PayModal(ref="PayModal" @query="query")
    //- 导出前弹窗
    ExportModal(ref="ExportModal" @query="query")
    //- 导出付款单弹窗(不带选择审批类型)
    ExportPDFModal(ref="ExportPDFModal" @query="query")
    //- 导出付款单弹窗(带选择审批类型)
    ExportPDFModal2(ref="ExportPDFModal2" @query="query")
    //- 查看付款弹窗
    LookPayListModal(ref="LookPayListModal" @query="query" @handleShowAuditDetailModal="handleShowAuditDetailModal")
    //- 流程审批单弹窗
    AuditDetailModal(ref="AuditDetailModal" @query="query")
    //- 选择审批方式弹窗
    //- ChooseTypeModal(ref="ChooseTypeModal" @query="query")
</template>

<script>
import { Common } from '@/utils/common.js'
import { FinancePayAccountApi } from '@/api/FinancePayAccount.api.js'
import { FinanceSSPayableApi } from '@/api/FinanceSSPayable.api.js'
import { ShouldPayableThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import ImportStandingBookModal from './modal/importStandingBookModal.vue'
import PayModal from "../publicModal/payModal.vue"
import ExportModal from "./modal/exportModal.vue"
import ExportPDFModal from "./modal/exportPDFModal.vue" // 不带选择审批类型
import ExportPDFModal2 from "./modal/exportPDFModal2.vue" // 带选择审批类型
import LookPayListModal from "../publicModal/lookPayListModal.vue"
import AuditDetailModal from "../publicModal/auditDetailModal.vue"
// import ChooseTypeModal from "../publicModal/chooseTypeModal.vue"
import dataApi from '@/api/data.js'
import { setTimeout } from 'timers';
// import expandRow from './table-expand.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: 'ssApplyList',

  components: {
    // expandRow
    ImportStandingBookModal,
    PayModal,
    ExportModal,
    ExportPDFModal,
    ExportPDFModal2,
    LookPayListModal,
    AuditDetailModal,
    // ChooseTypeModal
  },

  data () {
    return {
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      employeeId: '', // 员工ID
      thead: _cloneDeep(ShouldPayableThead),
      tableData: [],
      formData: {
        unitName: null,
        socialSecurityNo: this.$route.query.commonNo || null,
        status: null,
        feeYearMonthStart: new Date(),
        feeYearMonthEnd: new Date()
      },
      formItem: [
        { type: 'input', label: '编号所属单位：', placeholder: '请输入编号所属单位', prop: 'unitName', model: 'unitName', options: 'securityNos', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' },
        { type: 'select', label: '社保编号：', placeholder: '请输入社保编号', prop: 'socialSecurityNo', model: 'socialSecurityNo', options: 'securityNos', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' },
        { type: 'select', label: '状态：', placeholder: '请输入状态', prop: 'status', model: 'status', options: 'statusOps', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' },
        { type: 'interval', label: '费用月份：', placeholder1: '开始日期', prop1: 'feeYearMonthStart', model1: 'feeYearMonthStart', placeholder2: '结束日期', prop2: 'feeYearMonthEnd', model2: 'feeYearMonthEnd', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' }
      ],
      rules: {
        IdCardNo: [
          { type: 'string', message: '请输入正确的身份证号码', pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ]
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0, // 应付总计
      },
      downLoadRul: '',
      arrListDown: {
        securityNos: [],
        statusOps: [
        ],
        payAccount: [],
        PayType: []
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      },
      isDelete: false
    }
  },

  watch: {
  },
  computed: {
    isWorkFlow () {
      const workFlow = (JSON.parse(localStorage.getItem('clientLoginInfo'))).data.workFlow == 'true' ? true : false
      return workFlow
    },

    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    },
    // 导入
    hasImport () {
      return this.actionArr.indexOf('Import') > -1
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    // 删除
    hasDelete () {
      return this.actionArr.indexOf('Delete') > -1
    },
    // 强制删除
    hasForceDelete () {
      return this.actionArr.indexOf('ForceDelete') > -1
    },
    // 导出明细
    hasExportPayableDetail () {
      return this.actionArr.indexOf('ExportPayableDetail') > -1
    },
    // 申请付款
    hasPayApply () {
      return this.actionArr.indexOf('PayApply') > -1
    },
    // 生成付款单
    hasExportPayPDF () {
      return this.actionArr.indexOf('ExportPayPDF') > -1
    },
  },

  mounted () {
    this.getSelectIdList()
    this.getEnum()
    this.query()
    this.getSecurityNos()
    this.getPayAccount()
  },

  methods: {
    getSelectIdList () {
      let typeName = 'PayType'
      Common.getSelectIdList(typeName, this.arrListDown)
    },

    // 获取下拉
    async getEnum () {
      let groupNames = 'payablebills.apply.status'
      let res = await dataApi.getEnum({
        groupName: groupNames
      })
      this.arrListDown.statusOps = this.getItems(res.data, 'payablebills.apply.status')
    },
    getItems (arr, key) {
      let object = arr.find((item) => {
        return item.group === key
      })
      return object.items
    },

    // 获取付款账号
    async getPayAccount () {
      var params = {
        HasPaging: true,
        PageIndex: 1,
        PageSize: 5000,
        Status: 1
      }
      let res = await FinancePayAccountApi.getList(params)
      console.log('获取付款账号res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.payAccount = []
        res.data.data.map(item => {
          this.arrListDown.payAccount.push({label: item.unitName, value: item.id, bankName: item.bankName, accountNo: item.accountNo})
        })
      } else {
        this.arrListDown.payAccount = []
      }
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        IsApply: true
      }
      let res = await FinanceSSPayableApi.getSSPayableBillListApply({...params, ...this.formData})
      console.log('应付res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.total = res.data.total

        this.tableData.map(item => {
          item.feeDetails.map(i_item => { // 第一层表格中的数据拼接
            item[i_item.insuranceCode + 'should'] = i_item.should
          })
        })
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 获取保险编号
    async getSecurityNos () {
      var params = {
        type: 1,
        feedate: this.$moment(new Date()).format('YYYY-MM'),
        isall: 1
      }
      let res = await FinanceSSPayableApi.getSecurityNos(params)
      console.log('获取保险编号res: ', res)
      if (res.status === 200 && res.data.success) {
        // this.arrListDown.securityNos = res.data.data
        // this.$refs.ImportStandingBookModal.arrListDown.securityNos = res.data.data
        var arr = []
        res.data.data.map(item => {
          arr.push({value: item.securityNO, key: item.securityNO, companyGUID: item.companyGUID})
        })
        this.arrListDown.securityNos = arr
      } else {
        this.arrListDown.securityNos = []
      }
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择
    handleChangeDatePicker (val) {
      console.log('val: ', val)
      // this.formData.salaryMonth = val
      // this.getDayList()
    },

    // 导出社保应付账单
    async exportSSPayableBillDetail () {
      var params = {
        HasPaging: true,
        SocialSecurityNo: this.formData.socialSecurityNo,
        FeeYearMonthStart: this.formData.feeYearMonthStart,
        FeeYearMonthEnd: this.formData.feeYearMonthEnd,
        PageIndex: '',
        PageSize: '',
        Status: this.formData.status,
        UnitName: this.formData.unitName,
        IsApply: true,
      }
      console.log('params: ', params)
      let res = await FinanceSSPayableApi.exportSSPayableBillDetail(params)
      console.log('导出社保应付账单res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 导出明细前，填写月份和编号
    handleShowExportModal () {
      this.$refs.ExportModal.show()
      this.$refs.ExportModal.arrListDown = this.arrListDown
    },

    //  获取可申请余额
    async getApplyRest (row) {
      console.log('row: ', row)
      var params = {
        Year: row.periodYear,
        Month: row.periodMonth,
        SecurityNo: row.socialSecurityNo,
      }
      console.log('params: ', params)
      let res = await FinanceSSPayableApi.getApplyRest(params)
      console.log('获取可申请余额res: ', res)
      if (res.status === 200 && res.data.success) {
        this.getPayAccount()
        // this.handleShowExportPDFModal(row, res.data.data)
        if (this.isWorkFlow) {
          this.handleShowExportPDFModal2(row, res.data.data)
        } else {
          this.handleShowExportPDFModal(row, res.data.data)
        }
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 生成付款单前
    handleShowExportPDFModal (row, amt) {
      this.$refs.ExportPDFModal.arrListDown = this.arrListDown
      this.$refs.ExportPDFModal.show(row, amt)
    },

    // 生成付款单前2
    handleShowExportPDFModal2 (row, amt) {
      this.$refs.ExportPDFModal2.arrListDown = {...this.$refs.ExportPDFModal2.arrListDown, ...this.arrListDown}
      this.$refs.ExportPDFModal2.show(row, amt)
    },

    // 台账导入-显示弹窗
    handleShowImportStandingBookModal () {
      this.$refs.ImportStandingBookModal.show()
      this.$refs.ImportStandingBookModal.getSecurityNos()
      Object.keys(this.$refs.ImportStandingBookModal.formData).forEach(key => {
        if (key === 'feeYearMonth') {
          this.$refs.ImportStandingBookModal.formData[key] = this.$moment(new Date()).format('YYYY-MM')
        } else if (key === 'periodYear') {
          this.$refs.ImportStandingBookModal.formData[key] = this.$moment(new Date()).format('YYYY')
        } else if (key === 'periodMonth') {
          this.$refs.ImportStandingBookModal.formData[key] = this.$moment(new Date()).format('MM')
        } else {
          this.$refs.ImportStandingBookModal.formData[key] = ''
        }
      })
      console.log('弹窗表单: ', this.$refs.ImportStandingBookModal.formData)
    },

    // 查看付款-显示弹窗
    handleShowLookPayListModal (row) {
      this.$refs.LookPayListModal.parentRow = row
      this.$refs.LookPayListModal.modalType = 'socialSecurity'
      this.$refs.LookPayListModal.query(row)
      this.$refs.LookPayListModal.show()
    },

    // 去往应收差额说明
    gotoReceivableBalance (row) {
      var month = row.periodMonth < 10 ? '0' + row.periodMonth : row.periodMonth
      this.$router.push({
        path: '/financeReceivableBalance',
        name: 'financeReceivableBalance',
        query: {
          insureNo: row.socialSecurityNo,
          month: month,
          year: row.periodYear,
          date: row.periodYear + '-' + month
        }
      })
    },

    // 去往应付差额说明
    gotoPayableBalance (row) {
      var month = row.periodMonth < 10 ? '0' + row.periodMonth : row.periodMonth
      this.$router.push({
        path: '/financePayableBalance',
        name: 'financePayableBalance',
        query: {
          insureNo: row.socialSecurityNo,
          month: month,
          year: row.periodYear,
          date: row.periodYear + '-' + month
        }
      })
    },

    // 去往明细
    gotoDetail (row) {
      var month = row.periodMonth < 10 ? '0' + row.periodMonth : row.periodMonth
      this.$router.push({
        path: '/ssApplyDetail',
        name: 'ssApplyDetail',
        query: {
          insureNo: row.socialSecurityNo,
          month: month,
          year: row.periodYear,
          date: row.periodYear + '-' + month
        }
      })
    },

    // 是否删除前询问
    isDeleteModal (row) {
      this.$Modal.confirm({
        title: '是否确认删除该条信息',
        onOk: () => {
          this.handleDelete(row)
        }
      })
    },

    // 删除
    async handleDelete (row) {
      console.log('row: ', row)
      var params = {
        PeriodYear: row.periodYear,
        PeriodMonth: row.periodMonth,
        InsureNo: row.socialSecurityNo
      }
      console.log('params: ', params)
      let res = await FinanceSSPayableApi.delete(params)
      console.log('删除res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 是否强制删除前询问
    isForceDeleteModal (row) {
      this.$Modal.confirm({
        title: '数据删除后，已有的付款记录会同步删除，请确认！',
        onOk: () => {
          this.handleForceDelete(row)
        }
      })
    },

    // 强制删除
    async handleForceDelete (row) {
      console.log('row: ', row)
      var params = {
        PeriodYear: row.periodYear,
        PeriodMonth: row.periodMonth,
        InsureNo: row.socialSecurityNo
      }
      console.log('params: ', params)
      let res = await FinanceSSPayableApi.forceDelete(params)
      console.log('强制删除res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 付款-显示弹窗
    handleShowPayModal (row) {
      this.$refs.PayModal.getBankList()
      // this.$refs.PayModal.show()
      this.$refs.PayModal.modalType = 'socialSecurity'
      this.$refs.PayModal.formData.amount = row.total
      Object.keys(this.$refs.PayModal.socialSecurityParams).forEach(key => {
        this.$refs.PayModal.socialSecurityParams[key] = row[key]
      })
      this.$refs.PayModal.checkConfirmPay()
    },

    // 是否申请付款前询问
    isPayModal (row) {
      this.$Modal.confirm({
        title: '是否申请付款',
        onOk: () => {
          this.handlePayApply(row)
        }
      })
    },

    // 申请付款
    async handlePayApply (row) {
      console.log('row: ', row)
      var params = {
        Year: row.periodYear,
        Month: row.periodMonth,
        SecurityNo: row.socialSecurityNo
      }
      let res = await FinanceSSPayableApi.payApply(params)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 选择审批方式-显示弹窗
    // handleShowChooseTypeModal() {
    //   this.$refs.ChooseTypeModal.show()
    //   this.$refs.ChooseTypeModal.modalType = '社保付款申请'
    // },

    // 流程审批单-显示弹窗
    handleShowAuditDetailModal(row) {
      console.log('流程审批单-显示弹窗 row: ', row)
      this.$refs.AuditDetailModal.modalType = '社保审批详情'
      this.$refs.AuditDetailModal.show(row)
    }
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
